package com.franklin.java.api.ui.jpanel.checkbox;

import com.franklin.plugins.common.collection.PrettyArrayList;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 多选CheckBox
 * @author Franklin
 * @since 2021/9/1 9:59
 */
public class MultipleCheckBox extends JBPanel<MultipleCheckBox> {

    protected List<JBCheckBox> checkBoxList;

    protected List<String> itemList;

    public MultipleCheckBox(Collection<String> itemList, Collection<String> selectItemList) {
        this.itemList = itemList.stream().distinct().collect(Collectors.toList());
        init(selectItemList);
    }

    public MultipleCheckBox(Collection<String> selectItemList,String ... items) {
        this(Arrays.asList(items),selectItemList);
    }

    private void init(Collection<String> selectItemList){
        checkBoxList = new PrettyArrayList<>();
        Set<String> selected = new HashSet<>(selectItemList);
        itemList.forEach(item -> {
            JBCheckBox jbCheckBox = new JBCheckBox(item,selected.contains(item));
            checkBoxList.add(jbCheckBox);
            jbCheckBox.setHorizontalAlignment(SwingConstants.LEFT);
            this.add(jbCheckBox);
        });

    }

    public List<String> selectItems(){
        return this.checkBoxList
            .stream()
            .filter(AbstractButton::isSelected)
            .map(AbstractButton::getText)
            .collect(Collectors.toList());
    }

    public void addTail(String tail){
        this.add(new JBLabel(tail));
    }

    public void addActionListener(ActionListener actionListener){
        this.checkBoxList.forEach(jbCheckBox -> jbCheckBox.addActionListener(actionListener));
    }
}
